package com.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


/**
 * @author 王乾
 * @comments MD5密文工具类
 * @date 2024-05-10 22:39:25
 */
public class UtilMD5 {

    /**
     * @author 王乾
     * @comments 获取字符串MD5码
     * @date 2024-05-10 22:39:25
     * @return java.lang.String
     * @modification
     */
    public static String getMD5(String source) {
        return UtilMD5.getMD5(source.getBytes());
    }

    /**
     * @author 王乾
     * @comments 获取字符串MD5码
     * @date 2024-05-10 22:39:25
     * @return java.lang.String
     * @modification
     */
    public static String getMD5(String source, String charset) {
        String output = null;
        try {
            output = UtilMD5.getMD5(source.getBytes(charset));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return output;
    }

    /**
     * @author 王乾
     * @comments 获取字符数组MD5码
     * @date 2024-05-10 22:39:25
     * @return java.lang.String
     * @modification
     */
    public static String getMD5(byte[] in) {
        String result = null;
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            StringBuilder sbu = new StringBuilder();
            byte[] out = md5.digest(in);
            for (byte b : out) {
                int o = b & 0xFF;
                if (o < 16) {
                    sbu.append("0");
                }
                sbu.append(Integer.toHexString(o));
            }
            result = sbu.toString().toUpperCase();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }
}
